<template>
  <el-card shadow="hover">
    <template #header>
      <el-button type="primary" icon="ele-Plus" @click="showAddTrademarkDialogHandler()">添加</el-button>
    </template>

    <!-- 表格 -->
    <el-table :data="trademarks">
      <el-table-column label="序号" type="index" width="100px"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row }">
          <img :src="row.logoUrl" width="100" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px">
        <template #="{ row }">
          <el-button type="warning" icon="ele-Edit" @click="showAddTrademarkDialogHandler(row)">编辑</el-button>
          <el-button type="danger" icon="ele-Delete" @click="deleteTrademarkHandler(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px"
      :total="total"
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[5,10,15]"
      layout="prev,pager,next,jumper,->,sizes,total"
      @current-change="currentChangeHandler"
      @size-change="sizeChangeHandler"
    ></el-pagination>
  </el-card>

  <el-dialog v-model="isShowAddTrademarkDialog" :title="messageType + '品牌'">
    <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">

      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="formData.tmName"></el-input>
      </el-form-item>

      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="onSuccessHandler"
          :before-upload="beforeUploadHandler"
          >
          <img v-if="formData.logoUrl" class="avatar" :src="formData.logoUrl" />
          <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
        <el-button @click="isShowAddTrademarkDialog=false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademarkHandler">确定</el-button>
      </template>

  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "ProductTrademarkIndex",
});
</script>

<script lang="ts" setup>
import { ref,nextTick } from "vue";
import { requestTrademarkListByPage,requestSaveBaseTrademark,requestUpdateBaseTrademark,requestDeleteBaseTrademark } from "@/api/trademark";
import type { ReqSaveBaseTrademark, ResTrademark,ReqUpdateBaseTrademark } from "@/api/trademark"
import { ElMessage,ElMessageBox, type UploadFile, type UploadFiles, type FormRules,type UploadRawFile } from "element-plus";



const trademarks = ref<ResTrademark[]>([]);
console.log(trademarks);

const total = ref(0);
const page = ref(1);
const pageSize = ref(5);
const isShowAddTrademarkDialog = ref(false);
const formData = ref<ReqSaveBaseTrademark | ReqUpdateBaseTrademark>({
  tmName: "",
  logoUrl:""
})
const uploadUrl = `${import.meta.env.VITE_API_URL}/product/upload`
const formRef = ref()
const messageType = ref()

const rules:FormRules = {
  tmName:[
    {
      required:true,
      min:1,
      max:20,
      message:"品牌名称必须是1-20个字符之间",
      trigger: "blur",
    }
  ],
  logoUrl:[
    {
      required:true,
      validator(rule: any, value: string, callback) {
        // console.log("当前的value", value);
        if (value === "") {
          // 调用callback表示当前验证结束，callback中传入值表示有错误，不传入任何值，表示验证成功
          callback("品牌LOGO必填");
        } else {
          const ext = value.substring(value.lastIndexOf(".") + 1);
          // console.log(ext);
          if (!["png", "jpg", "gif"].includes(ext)) {
            callback("品牌LOGO必须是图片");
          } else {
            callback();
          }
        }
      },
    }
  ]
}

/**
 * 请求trademark
 */
async function getTrademarkListByPage() {
  try {
    const res = await requestTrademarkListByPage(page.value,pageSize.value);
    console.log(res);

    trademarks.value = res.records;
    total.value = res.total;
    page.value = res.current;
    pageSize.value = res.size

  } catch (e) {}
}

getTrademarkListByPage();

// 监听分页器的当前页面变化
function currentChangeHandler(v: number) {
  page.value = v;
  getTrademarkListByPage()
}

// 监听分页器的每页显示条数变化
function sizeChangeHandler(v:number) {
  pageSize.value = v;
  getTrademarkListByPage()
}

// 监听添加和编辑品牌按钮的点击
function showAddTrademarkDialogHandler(data:ResTrademark) {
  // console.log(data);
  
  isShowAddTrademarkDialog.value = true;

  if (data) {
    formData.value = { ...data };
    messageType.value = "修改"
  } else {
    formData.value = {
    tmName:"",
    logoUrl:""
  }
  messageType.value = "添加"
  }

  
  nextTick(() => {
    formRef.value?.clearValidate()
  })

}

/**
 * 图片上传之前
 * (rawFile: UploadRawFile) => Awaitable<void | undefined | null | boolean | File | Blob>
 * 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
 */
function beforeUploadHandler(rawFile: UploadRawFile) {
  console.log(rawFile);
  
  if (!["image/jpg","image/png","image/gif"].includes(rawFile.type)) {
    return false;
  }
  if (rawFile.size > 102400) {
    return false
  }
}

// 图片上传成功后
function onSuccessHandler(
  response:{code:number;data:string},
  uploadFile:UploadFile,
  uploadFiles:UploadFiles
) {
  if (response.code == 200) {    
    formData.value.logoUrl = response.data;
    console.log(formData.value.logoUrl);
    
  }
}

// 添加确定提交品牌数据
async function addOrUpdateTrademarkHandler() {
  
  try {
    // console.log("formRef",formRef.value);
    
    try {
      const res = await formRef.value.validate();
      
      // console.log(111);
      isShowAddTrademarkDialog.value = false;
      if (messageType.value == "修改") {
        await requestUpdateBaseTrademark(formData.value as ReqUpdateBaseTrademark)
      } else {
        // 添加
        await requestSaveBaseTrademark(formData.value as ReqSaveBaseTrademark);
        page.value = Math.ceil((total.value + 1) / pageSize.value)
      }
      ElMessage.success(messageType.value + "成功");
      getTrademarkListByPage()

    } catch (e) {
      console.log("校验失败",e);
    }

  } catch (e) {
    ElMessage.error(messageType.value + "失败")
  }
}

// 删除指定的品牌
async function deleteTrademarkHandler(id:number) {
  try {
    try {
      await ElMessageBox({
        title:"提示",
        message:"你确定要删除吗",
        icon:"ele-Delete"
      })
      await requestDeleteBaseTrademark(id)
      ElMessage.success("删除成功")
      getTrademarkListByPage()
    } catch (e) {}

  } catch (e) {
    ElMessage.error("删除失败")
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

